package logic

import (
	"context"
	"fmt"
	"github.com/dustin/go-humanize"
	"meituan-waimai/meituanrpc/internal/svc"
	"meituan-waimai/meituanrpc/meituanrpc"
	"meituan-waimai/models/mysql"
	"meituan-waimai/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type PayOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPayOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayOrderLogic {
	return &PayOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PayOrderLogic) PayOrder(in *meituanrpc.PayOrderRequest) (*meituanrpc.PayOrderResponse, error) {
	// todo: add your logic here and delete this line
	var order mysql.Order
	mysql.DB.Where("id = ?", in.OrderId).First(&order)
	if order.ID == 0 {
		return nil, fmt.Errorf("订单不存在")
	}
	// 订单金额转字符串
	OrderAmount := humanize.Ftoa(order.OrderAmount)
	// 判断优惠券是否存在
	var coupon mysql.Coupon
	mysql.DB.Where("id = ?", in.CouponId).First(&coupon)
	if coupon.ID == 0 {
		return nil, fmt.Errorf("优惠券不存在")
	}
	// 判断优惠券是否属于该用户
	if int(order.UserId) != coupon.UserId {
		return nil, fmt.Errorf("非法的优惠券")
	}
	// 判断优惠券是否使用
	if coupon.CouponStatus == 1 {
		return nil, fmt.Errorf("已核销的优惠券无法重复使用")
	}
	pay := pkg.AliPay(order.OrderNo, order.OrderTitle, OrderAmount)
	// 订单交易已创建，将优惠券与订单绑定，方便核销
	order.CouponId = int64(coupon.ID)
	mysql.DB.Updates(&order)
	// 订单交易已创建，开始更新订单状态
	order.OrderStatus = "已下单，待支付"
	mysql.DB.Updates(&order)
	return &meituanrpc.PayOrderResponse{
		Url: pay,
	}, nil
}
